package com.cropdoctor.common;

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Data
@NoArgsConstructor
@AllArgsConstructor
@ApiModel(value = "result",description = "统一返回数据")
public class Result<T> {
    @ApiModelProperty(value = "返回数据编码",required = true)
    public Integer code; //返回编码

    @ApiModelProperty(value = "错误相关信息",required = false)
    public String msg;//错误相关信息

    @ApiModelProperty(value = "其他数据",required = false)
    public Map map = new HashMap(); //动态数据

    @ApiModelProperty(value = "返回数据",required = false)
    public T data;


    public static <T> Result<T> success(T data) {
        Result<T> result = new Result<>();
        result.code = ResultCode.SUCCESS.getCode();//服务正常代码
        result.data = data;
        result.msg = ResultCode.SUCCESS.getMessage();
        return result;
    }

    public static <T> Result<T> success() {
        Result<T> result = new Result<>();
        result.code = ResultCode.SUCCESS.getCode();//服务正常代码
        result.msg = ResultCode.SUCCESS.getMessage();
        return result;
    }

    public static <T> Result<T> error(String msg){
        Result<T> result = new Result<>();
        result.code = ResultCode.COMMON_FAIL.getCode();//未传入错误代码则默认commonfail
        result.msg = msg;
        return result;
    }

    public static <T> Result<T> error(ResultCode resultEnum){
        Result<T> result = new Result<>();
        result.code = resultEnum == null ? ResultCode.COMMON_FAIL.getCode() : resultEnum.getCode();
        result.msg = resultEnum == null ? ResultCode.COMMON_FAIL.getMessage() : resultEnum.getMessage();
        return result;
    }

    public static <T> Result<T> error(ResultCode resultEnum,T data){
        Result<T> result = new Result<>();
        result.data = data;
        result.code = resultEnum == null ? ResultCode.COMMON_FAIL.getCode() : resultEnum.getCode();
        result.msg = resultEnum == null ? ResultCode.COMMON_FAIL.getMessage() : resultEnum.getMessage();
        return result;
    }

    public Result<T> add(String key, Object value){
        this.map.put(key,value);
        return this;
    }

}
